import { useState, useCallback, useEffect, useRef } from "react";
import { useDispatch } from "react-redux";
import { useNavigate, useParams } from 'react-router-dom';
import CommonService from "../../app/services/commonService";
import UserService from "../../app/services/userService";
import UserBasicInfoCompact from "../components/userBasicInfoCompact";
import UserIntentCompact from "../components/userIntentCompact";
import { NotificationManager } from 'react-notifications';
import EmptyUniversityRow from "./components/emptyUniversity";
import CompanyUserService from "../../app/services/companyUserService";
import AccountSheetService from "../../app/services/accountSheetService";
import MajorItem from "./components/majorItem";
import TrashIcon from "@heroicons/react/24/outline/TrashIcon";
import UniversityMajorView from "./components/universityMajorView";
import ConfirmDialog from "../../components/ConfirmDialog";
import { PrinterIcon } from "@heroicons/react/24/outline";
import { setShow } from "../../app/store/leftBarStatusSlice";
import ReactToPrint from 'react-to-print';


import _ from "lodash";

function SheetEditor() {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const divRef = useRef(null);
    const printRef = useRef(null);
    const params = useParams();

    const [data, setData] = useState({});
    const [sheetData, setSheetData] = useState([]);
    const [regionIntentions, setRegionIntentions] = useState([]);
    const [selectUniversityId, setSelectUniversityId] = useState(0);
    const [selectedRowSortIndex, setSelectedRowSortIndex] = useState(null);
    const [showConfirmDialog, setShowConfirmDialog] = useState(false);
    const [alertMessage, setAlertMessage] = useState('');
    const [printMode, setPrintMode] = useState(false);

    // 删除专业还是删除院校
    const [removeMajorMode, setRemoveMajorMode] = useState(true);
    //删除功能使用
    const [selectedSheetId, setSelectedSheetId] = useState(null);
    const [sortIndex, setSortIndex] = useState(null);
    // 专业选择
    const [selectedMajorSortIndex, setSelectedMajorSortIndex] = useState(0);

    const fetchData = useCallback(async () => {
        CommonService.setLoading(true);
        CompanyUserService.studentDetail(params.id).then((res) => {
            if (res.success) {
                setData(res.data);
                const regionIntentions = res.data.universityRegions.map(item => item.province);
                setRegionIntentions(regionIntentions)
            }
        }).finally(() => {
            CommonService.setLoading(false);
        });
    }, [params.id]);

    const fetchSheetData = useCallback(async () => {
        loadData()
    }, [params.id]);

    const loadData = () => {
        CommonService.setLoading(true);
        CompanyUserService.getUserSheetDetail(params.id, 2).then((res) => {
            if (res.success) {
                setSheetData(res.data);
            }
        }).finally(() => {
            CommonService.setLoading(false);
        });
    }

    useEffect(() => {
        fetchData();
        fetchSheetData();
    }, [params.id])

    const showAddUniversityModal = (sortIndex) => {
        setSelectUniversityId(0)
        setSelectedRowSortIndex(sortIndex)
        divRef.current.showModal();
    }

    const onMajorDelete = (sheetItemId, majorSortIndex) => {
        setSelectedSheetId(sheetItemId);
        setSortIndex(majorSortIndex);
        setAlertMessage('确认删除当前专业?');
        setRemoveMajorMode(true);
        setShowConfirmDialog(true);
    }

    const onUnivDelete = (sheetItemId) => {
        setSelectedSheetId(sheetItemId);
        setSortIndex(null);
        setAlertMessage('确认删除当前院校?');
        setRemoveMajorMode(false);
        setShowConfirmDialog(true);
    }

    const onConfirmCancel = () => {
        setShowConfirmDialog(false);
    }

    const onConfirmSuccess = () => {
        const func = removeMajorMode ? AccountSheetService.removeSheetMajor : AccountSheetService.removeUniversity;
        CommonService.setLoading(true);
        func({
            relationId: params.id,
            sheetItemId: selectedSheetId,
            majorSortIndex: sortIndex
        }).then(res => {
            if (res.success) {
                NotificationManager.success('删除成功');
                loadData();
            } else {
                NotificationManager.error(`删除失败:${res.message}`);
            }

        }).finally(() => {
            CommonService.setLoading(false);
        })
        setShowConfirmDialog(false);
    }

    const addMajorToClonedSheet = (universityId, batch, majorName) => {
        const data = {
            relationId: params.id,
            universityId: universityId,
            batch: batch,
            majorName: majorName,
            universitySortIndex: selectedRowSortIndex,
            majorSortIndex: selectedMajorSortIndex
        }

        CommonService.setLoading(true);
        AccountSheetService.addSheetMajor(data).then((res) => {
            if (res.success) {
                NotificationManager.success('添加成功');
                divRef.current.close();
                loadData();
            } else {
                NotificationManager.error(`添加失败:${res.message}`);
            }
        }).finally(() => {
            CommonService.setLoading(false);
        });
    }

    const onMajorItemAdd = (sortIndex, universityId, majorSortIndex) => {
        setSelectedRowSortIndex(sortIndex);
        setSelectUniversityId(universityId);
        setSelectedMajorSortIndex(majorSortIndex);
        divRef.current.showModal();
    }



    return (
        <>
            <ConfirmDialog title="提示" showModel={showConfirmDialog} onCancel={onConfirmCancel} onSuccess={onConfirmSuccess}><div className=" text-sm">{alertMessage}</div></ConfirmDialog>
            <dialog className={`modal`} ref={divRef}>
                <div className="modal-box w-full max-w-5xl h-full">
                    <UniversityMajorView universityId={selectUniversityId} relationId={params.id} sortIndex={selectedRowSortIndex}
                        addMajorToClonedSheet={(scoreItem) => addMajorToClonedSheet(scoreItem.universityId, scoreItem.batch, scoreItem.majorName,)} />
                    <div className="modal-action fixed bottom-2 right-2 bg-base-100">
                        <form method="dialog">
                            <button className="btn">关闭</button>
                        </form>
                    </div>
                </div>
            </dialog>
            <div className="flex flex-row items-center justify-end p-4 fixed right-4 top-16 z-50">
                    <a className="btn btn-square" href={`/#/app/SheetEditorPrint/${params.id}`} target='_blank'>
                        <PrinterIcon className="w-8 h-8 text-green-500" />
                    </a>                
            </div>

            <div className="w-full flex flex-col p-4 card  bg-base-100" ref={printRef}>
                <div className="flex flex-col rounded-md shadow-lg bg-base-100" style={{ width: printMode ? '1600px' : '100%' }}>
                    <div className=" flex flex-row items-center justify-center text-lg font-bold m-2 p-2">
                        {data.userName}的志愿单
                    </div>
                    <UserBasicInfoCompact basicInfo={data.basicInfo} />
                    <UserIntentCompact title="区域意向" intents={regionIntentions} />
                    <UserIntentCompact title="院校类型" intents={data.universityAttrs} />

                    {/* </div>
                <div className=" rounded-md shadow-lg p-2 overflow-hidden overflow-x-auto overflow-y-auto card  bg-base-100" > */}
                    <table className="table table-zebra rounded-sm  border-1 mt-2">
                        <thead className="">
                            <tr className="bg-base-300  text-sm text-center">
                                <th className=" ">序号</th>
                                <th>院校名称</th>
                                <th width='120px'>历年分数</th>
                                <th>专业1</th>
                                <th>专业2</th>
                                <th>专业3</th>
                                <th>专业4</th>
                                <th>专业5</th>
                                <th>专业6</th>
                                {!printMode && <th>操作</th>}
                            </tr>
                        </thead>
                        <tbody>
                            {sheetData && sheetData.length > 0 ? (
                                sheetData.map((item, index) => {
                                    return (
                                        <>
                                            {item.universityId !== null ?
                                                <tr key={index}>
                                                    <th className=" text-center">{item.index}</th>
                                                    <td className=" text-center">
                                                        <div className="flex flex-col items-center justify-center text-xs p-1">
                                                            <div className=" text-base font-semibold">{item.universityName}</div>
                                                            <div>{item.enrollCode}</div>
                                                            <div className={` font-semibold ${item.type === '民办' ? 'text-red-500' : 'text-green-500'}`}>{item.type}</div>
                                                            <div>{item.tags}</div>
                                                        </div>
                                                    </td>
                                                    <td className=" text-center">
                                                        <div className="flex flex-col items-center justify-center text-xs">
                                                            {
                                                                item.scoreInfos && item.scoreInfos.length > 0 && item.scoreInfos.map((scoreItem, scoreIndex) => {
                                                                    return (<div key={scoreIndex} className="flex flex-row items-center justify-center text-xs p-1 border-b-2">
                                                                        <div className="flex flex-col items-center justify-center">
                                                                            <div>{scoreItem.year}年</div>
                                                                            <div>{scoreItem.batch.replace('本科', '')}/{scoreItem.submitType}</div>
                                                                            <div>{scoreItem.minScore}分</div>
                                                                            <div>{scoreItem.minScoreRank}位</div>
                                                                        </div>
                                                                    </div>)
                                                                })}
                                                        </div>
                                                    </td>
                                                    <td className=" text-center">
                                                        <MajorItem printMode={printMode} major={item.major1} onMajorDelete={() => onMajorDelete(item.id, 0)} onMajorItemAdd={() => onMajorItemAdd(item.sortIndex, item.universityId, 0)} />
                                                    </td>
                                                    <td className=" text-center">
                                                        <MajorItem printMode={printMode} major={item.major2} onMajorDelete={() => onMajorDelete(item.id, 1)} onMajorItemAdd={() => onMajorItemAdd(item.sortIndex, item.universityId, 1)} />
                                                    </td>
                                                    <td className=" text-center">
                                                        <MajorItem printMode={printMode} major={item.major3} onMajorDelete={() => onMajorDelete(item.id, 2)} onMajorItemAdd={() => onMajorItemAdd(item.sortIndex, item.universityId, 2)} />
                                                    </td>
                                                    <td className=" text-center">
                                                        <MajorItem printMode={printMode} major={item.major4} onMajorDelete={() => onMajorDelete(item.id, 3)} onMajorItemAdd={() => onMajorItemAdd(item.sortIndex, item.universityId, 3)} />
                                                    </td>
                                                    <td className=" text-center">
                                                        <MajorItem printMode={printMode} major={item.major5} onMajorDelete={() => onMajorDelete(item.id, 4)} onMajorItemAdd={() => onMajorItemAdd(item.sortIndex, item.universityId, 4)} />
                                                    </td>
                                                    <td className=" text-center">
                                                        <MajorItem printMode={printMode} major={item.major6} onMajorDelete={() => onMajorDelete(item.id, 5)} onMajorItemAdd={() => onMajorItemAdd(item.sortIndex, item.universityId, 5)} />
                                                    </td>
                                                    {!printMode && <td className=" text-center">
                                                        <button className="btn btn-square  hover:bg-base-300" onClick={() => onUnivDelete(item.id)}><TrashIcon className="w-8 h-8 text-red-500" /></button>
                                                    </td>
                                                    }
                                                </tr> :
                                                <tr key={index}>
                                                    <th className=" text-center">{item.index}</th>
                                                    <td className=" text-center" colSpan={8}>
                                                        <EmptyUniversityRow printMode={printMode} addUniversity={() => showAddUniversityModal(item.sortIndex)} />
                                                    </td>
                                                </tr>}
                                        </>
                                    );
                                })
                            ) : (
                                <tr>
                                    <td colSpan="7">暂无数据</td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                    <div className="flex flex-col items-start justify-center text-xs font-bold m-2 p-2">
                        <div>提示：</div>
                        <p>1.本志愿单提供的数据数据来源于歌声教育考试院和高校官方公布信息，提供的信息仅供您参考，请以各高校或各省教育考试院正式公布的数据为准。</p>
                        <p>2.不保证所推荐的志愿填报方案必然能够导致用户得到录取，对用户或计算结果提供的资料、数据及内容也不作其他任何形式的担保(不论是明确的或隐含的，包括所有有关信息真实性、适当性、适于某一特定用途、所有权和非侵权性的默示担保和条件)</p>
                    </div>
                </div>
            </div>
        </>
    );
}

export default SheetEditor;
